<template>
	<view>
		<!-- //1 样式不同 2 值可输入还要回显 3增加删除值动态修改 4 不能输入0 -->
		<view class="inputflex">
			<uni-icons @click.stop="jian" v-show="localValue>0" type="minus" size="26" color="#FF7700"></uni-icons>
			<input v-show="localValue>0" @focus='inputfocus' @blur='inputblur' :value="localValue" type="number"
				@input="handleInput" confirm-type="done" />
			<uni-icons type="plus-filled" size="26" color="#FF7700" @click.stop="add"></uni-icons>
		</view>
	</view>
</template>


<script setup>
	import {
		ref,
		watch
	} from 'vue';
	import {
		useStore
	} from 'vuex';
	import {
		setShopCarCount,removeShopCar
	} from '@/common/http.api.js';
	const store = useStore();
	// 接收父组件传来的 modelValue 
	// modelValue为约定俗成字段，就是父组件传来的v-model绑定的值
	const props = defineProps({
		shop:{
			type:Object,
			default: ''
		},
		modelValue: {
			type: [String, Number],
			default: ''
		}
	});
	// update:modelValue也是固定的
	const emit = defineEmits(['update:modelValue']);
	// 本地状态
	const localValue = ref(props.modelValue);
	// 当父组件的 modelValue 发生变化时，更新本地状态
	watch(
		() => props.modelValue,
		newValue => {
			localValue.value = newValue;
		}
	);
	// 当 input 的值发生变化时，通知父组件
	const handleInput = (event) => {
		localValue.value = event.target.value
	};
	function add() {
		localValue.value++
		setCount()
	}
	function jian() {
		localValue.value--
		if(localValue.value==0){
			removeShopCar({ids:[props.shop.id]}).then(res=>{
				if(res.code == 200){
					uni.showToast({
						title: '商品移除购物车',
						icon: 'none'
					})
					let total= res.data.reduce((sum, e) => sum + Number(e.productCount || 0), 0)
					store.commit('setShopNum', total)
				}
			})
		}else{
			setCount()
		}
	}
	function inputblur() {
		if (localValue.value < 1) {
			uni.showToast({
				title: '最小值为1',
				icon: 'none'
			})
			localValue.value = 1
			setCount()
		}else{
			setCount()
		}
	}
	function setCount(){
		setShopCarCount({
			productId:props.shop.id,
			productCount:localValue.value
		}).then(res=>{
			if(res.code == 200){
				let total= res.data.reduce((sum, e) => sum + Number(e.productCount || 0), 0)
				emit('update:modelValue', localValue.value);
				store.commit('setShopNum', total)
			}
		})
	}
</script>


<style lang="scss">
	.inputflex {
		display: flex;
		height: 46rpx;
		text-align: center;
		align-items: center;

		input {
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 30rpx;
			color: #FF0000;
			max-width: 60rpx;
			line-height: 46rpx;
		}
	}
</style>